
#include <iostream>
#include <vector>
#include <string>
#include <memory>

// 观察者接口
class Observer {
public:
    virtual ~Observer() = default;
    virtual void update(const std::string& stockName, double price) = 0;
};

// 主题接口
class Subject {
public:
    virtual ~Subject() = default;
    virtual void attach(const std::shared_ptr<Observer>& observer) = 0;
    virtual void detach(const std::shared_ptr<Observer>& observer) = 0;
    virtual void notify() = 0;
};

// 具体主题
class Stock : public Subject {
private:
    std::string name_;                         // 股票名称
    double price_;                             // 当前价格
    std::vector<std::shared_ptr<Observer>> observers_; // 观察者列表

public:
    explicit Stock(const std::string& name, double price) : name_(name), price_(price) {}

    void setPrice(double price) {
        if (price_ != price) {
            price_ = price;
            notify(); // 通知观察者
        }
    }

    double getPrice() const {
        return price_;
    }

    std::string getName() const {
        return name_;
    }

    void attach(const std::shared_ptr<Observer>& observer) override {
        observers_.push_back(observer);
    }

    void detach(const std::shared_ptr<Observer>& observer) override {
        observers_.erase(std::remove(observers_.begin(), observers_.end(), observer), observers_.end());
    }

    void notify() override {
        for (const auto& observer : observers_) {
            observer->update(name_, price_);
        }
    }
};

// 具体观察者
class Investor : public Observer {
private:
    std::string name_;

public:
    explicit Investor(const std::string& name) : name_(name) {}

    void update(const std::string& stockName, double price) override {
        std::cout << "Investor [" << name_ << "] notified: Stock [" << stockName
                  << "] has a new price: $" << price << "\n";
    }
};

// 客户端代码
int main() {
    auto stock = std::make_shared<Stock>("TechCorp", 150.0);

    auto investor1 = std::make_shared<Investor>("Alice");
    auto investor2 = std::make_shared<Investor>("Bob");

    stock->attach(investor1);
    stock->attach(investor2);

    std::cout << "Initial Stock Price: $" << stock->getPrice() << "\n";

    stock->setPrice(155.0); // 改变价格，触发通知
    stock->setPrice(160.0);

    stock->detach(investor1); // 移除观察者

    stock->setPrice(165.0); // 只有 Bob 接收通知

    return 0;
}


